<script>
import { atLeastN } from '@/utils/kris_utils'
import list2 from './list2.vue'

import CreateApartment from './components/CreateApartment'
import DeleteApartment from './components/DeleteApartment'
import EditApartment from './components/EditApartment'
import RoomOverview from './components/RoomOverview'
import { getDormitory } from '@/api/v2/basic'
import { delDorm } from '@/api/v2/dorm'
export default {
  components: {
    list2,
    CreateApartment,
    DeleteApartment,
    EditApartment,
    RoomOverview
  },
  data() {
    return {
      apartments: [],
      pagination: {
        size: 10,
        current: 1,
        total: 0
      },
      loadingStatuses: {
        loading: false
      },

      createApartmentDialog: {
        visible: false
      },
      editApartmentDialog: {
        visible: false,
        apartment: null
      },

      selectedRows: [],
      isDeleting: false,
      form: {}
    }
  },
  computed: {
    roomsFormatted() {
      return this.apartments.map((item) => {
        const { id, address, rent, room_count, photo, room } = item

        let capacity = 0
        let used = 0

        if (atLeastN(room, 1)) {
          capacity = room.reduce((prev, current) => {
            return prev + (current?.number ?? 0)
          }, 0)

          used = room.reduce((prev, current) => {
            return prev + (current?.fieldData?.length ?? 0)
          }, 0)
        }

        return {
          id,
          address,

          capacity,
          used,

          rent: parseFloat(rent),
          roomCount: room_count,
          photos: this.parsePhotos(photo),
          rooms: room
        }
      })
    },

    roomList() {
      return this.roomsFormatted.map(item => {
        return {
          ...item,
          rooms: item.rooms.map(room => {
            return {
              apartmentId: room.dormitory_id,
              id: room.id,
              name: room.name,
              employees: room.fieldData,
              remain: room?.spare_bed
            }
          })
        }
      })
    },
    isActionDisabled() {
      return this.loadingStatuses.loading || this.isDeleting
    }
  },
  created() {
    this.initData()
  },
  methods: {
    atLeastN,
    parsePhotos(photos) {
      try {
        return JSON.parse(photos)
      } catch (e) {
        return []
      }
    },
    showCreateApartmentDialog() {
      this.createApartmentDialog.visible = true
    },

    // 分页
    handlePageChange(currentPage) {
      this.pagination.current = currentPage
      this.refreshTable()
    },
    handlePageSizeChange(size) {
      this.pagination.size = size
      this.refreshTable()
    },

    // 创建结果事件回调
    handleCreateSuccess(result) {
      this.$message.success(result.message ?? '创建成功')
      this.createApartmentDialog.visible = false
      this.refreshTable()
    },
    handleCreateFailed(e) {
      this.$message.error(e.message ?? '创建失败')
    },

    // 修改事件结果
    handleUpdateSuccess(result) {
      this.$message.success(result.message ?? '修改成功')
      this.editApartmentDialog.visible = false
      this.refreshTable()
    },
    handleUpdateFailed(e) {
      this.$message.error(e.message ?? '修改失败')
    },

    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },
    handleSelectionChange(e) {
      this.selectedRows = e
    },
    handleEditApartment(apartment) {
      const { id, address, photos, rent } = apartment
      this.editApartmentDialog.apartment = { id, address, photos, rent }
      this.editApartmentDialog.visible = true
      console.log(this.editApartmentDialog.apartment)
    },
    async batchDelete() {
      await this.$confirm('您确定要删除这些数据吗?', '提示')
      if (this.selectedRows.length <= 0) return
      try {
        const ids = this.selectedRows.map((item) => item.id)
        const params = {
          id: JSON.stringify(ids)
        }
        this.isDeleting = true
        await this.sleep(300)
        const result = await delDorm(params)

        this.isDeleting = false
        this.refreshTable()
        this.$message.success(result?.message ?? `成功删除${ids.length}条数据`)
      } catch (e) {
        this.isDeleting = false
        this.$message.error(e?.message ?? '删除失败')
      }
    },
    async refreshTable() {
      try {
        if (this.loadingStatuses.loading) return
        this.loadingStatuses.loading = true
        await this.sleep(400)
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      }
    },
    async getApartments() {
      const { size, current } = this.pagination
      const { address, minrent, maxrent, number, username } = this.form
      const params = {
        paginate: size,
        page: current,
        address: address,
        minrent: minrent,
        number: number,
        username: username,
        maxrent: maxrent
      }
      const result = await getDormitory(params)
      this.apartments = result?.data ?? []
      this.pagination.total = result?.meta?.total ?? 0
    },
    async loadData() {
      const result = await Promise.allSettled([this.getApartments()])
      const failTasks = result.filter((item) => item.status === 'rejected')
      if (failTasks.length <= 0) return
      throw failTasks.at(0)
    },
    async initData() {
      try {
        this.loadingStatuses.loading = true
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      }
    },
    onSubmit() {
      this.getApartments()
    },
    handleDetails(row) {
      console.log(row)
      this.$router.push(`/dormitory/show/${row.id}`)
    }
  }
}
</script>

<template>
  <!-- <list2 /> -->
  <div class="app-container room-container">
    <CreateApartment
      v-model="createApartmentDialog.visible"
      @success="handleCreateSuccess"
      @failed="handleCreateFailed"
    />

    <EditApartment
      v-model="editApartmentDialog.visible"
      :apartment="editApartmentDialog.apartment"
      @success="handleUpdateSuccess"
      @failed="handleUpdateFailed"
    />

    <div class="card">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="居住人员">
          <el-input v-model="form.username" placeholder="请输入居住人员姓名" />
        </el-form-item>
        <el-form-item label="宿舍地址">
          <el-input v-model="form.address" placeholder="请输入宿舍地址" />
        </el-form-item>
        <el-form-item label="宿舍总租金范围">
          <div style="display: flex">
            <el-input
              v-model="form.minrent"
              placeholder="请输入租金最小值"
            />
            <span class="lineae">至</span>
            <el-input
              v-model="form.maxrent"
              placeholder="请输入租金最大值"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card style="border: none;" shadow="never">
      <el-row :gutter="40" justify="center">
        <el-col :span="24">
          <div class="header-container">
            <el-button
              class="header-container__item"
              type="primary"
              icon="el-icon-plus"
              @click="showCreateApartmentDialog"
            >
              创建宿舍
            </el-button>

            <el-button
              class="header-container__item"
              icon="el-icon-refresh-right"
              :disabled="loadingStatuses.loading"
              @click="refreshTable"
            >
              刷新
            </el-button>

            <el-tooltip
              effect="dark"
              content="请勾选需要删除的宿舍"
              placement="bottom"
              :disabled="selectedRows.length > 0"
            >
              <span class="header-container__item">
                <el-button
                  icon="el-icon-delete"
                  type="danger"
                  :disabled="isActionDisabled || selectedRows.length <= 0"
                  :loading="isDeleting"
                  @click="batchDelete"
                >
                  批量删除
                </el-button>

              </span>
            </el-tooltip>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-table
            v-loading="loadingStatuses.loading"
            :data="roomList"
            row-key="id"
            style="width: 100%"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" />
            <el-table-column label="地址" align="center">
              <template slot-scope="scope">
                <div slot="reference" class="name-wrapper">
                  {{ scope.row.address }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="roomCount" label="房间数量" align="center" />
            <el-table-column label="可住/已住" align="center">
              <template slot-scope="scope">
                {{ scope.row.capacity }} / {{ scope.row.used }}
                <el-popover trigger="click" placement="top" title="房间概览">
                  <el-empty
                    v-if="scope.row.rooms.length <= 0"
                    description="暂无房间"
                  />
                  <template v-else>
                    <RoomOverview
                      v-for="(room, roomIndex) in scope.row.rooms"
                      :key="roomIndex"
                      :room="room"
                    />
                  </template>

                  <el-button slot="reference" type="text">
                    <i class="el-icon-view" />
                  </el-button>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="rent" label="租金" align="center" />
            <el-table-column label="照片" align="center" width="320px">
              <template slot-scope="scope">
                <el-image
                  v-if="atLeastN(scope.row.photos, 1)"
                  style="width: 40px; height: 40px"
                  :src="scope.row.photos[0]"
                  :preview-src-list="scope.row.photos"
                />
                <el-tag v-else size="small" type="warning">未上传</el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="actions" label="操作" align="center" width="280px">
              <template slot-scope="scope">
                <div class="actions">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleEditApartment(scope.row)"
                  >编辑</el-button>
                  <DeleteApartment
                    :apartment-id="scope.row.id"
                    @success="refreshTable"
                  />
                  <el-button
                    type="success"
                    size="small"
                    @click="handleDetails(scope.row)"
                  >详情</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-pagination
            class="block"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pagination.current"
            :page-sizes="[10, 50, 100]"
            :page-size="pagination.size"
            :total="pagination.total"
            :disabled="loadingStatuses.loading"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<style lang="scss">
.room-container {

  .card {
    border-radius: 4px;
    background-color: #fff;
    margin-bottom: 20px;
    padding: 20px 20px 0 20px;
  }

  ::v-deep(.el-form-item) {
    margin-bottom: 20px;
    //margin-right: 20px;
  }

  .header-container {
    padding-bottom: 20px;

    &__item {
      margin-right: 10px;
    }
  }

  .el-pagination {
    padding: 16px 0;

    .btn-prev,
    .btn-next {
      margin: 0;
      margin-right: 6px;
    }
  }

  .actions {
    display: flex;
    justify-content: center;
    align-items: center;
    .el-button {
      margin: 5px;
    }
  }
}
.lineae {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 10px;
}
.block{
  display: flex;
  justify-content: center;
}
</style>
